package com.sgg.spzx.service.impl;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sgg.spzx.exception.CustomException;
import com.sgg.spzx.mapper.SysUserMapper;
import com.sgg.spzx.model.dto.system.LoginDto;
import com.sgg.spzx.model.entity.system.SysUser;
import com.sgg.spzx.model.vo.common.ResultCodeEnum;
import com.sgg.spzx.model.vo.system.LoginVo;
import com.sgg.spzx.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public LoginVo login(LoginDto loginDto) {
        String userName = loginDto.getUserName();
        SysUser sysUser =  sysUserMapper.selectUserInfoByUserName(userName);
        if (sysUser == null) {
//            throw new RuntimeException("用户不存在");
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }
        String dbbase_password = sysUser.getPassword();
        String input_password = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());
        if (!input_password.equals(dbbase_password)){
//            throw new RuntimeException("密码不正确");
            throw new CustomException(ResultCodeEnum.LOGIN_ERROR);
        }
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        stringRedisTemplate.opsForValue().set("user:login"+ token, JSONUtil.parseObj(sysUser).toString(), 7, TimeUnit.DAYS);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userJson = stringRedisTemplate.opsForValue().get("user:login"+token);
        SysUser sysUser = JSONUtil.toBean(userJson, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        stringRedisTemplate.delete("user:login"+token);
    }
}
